# -*- coding: utf-8 -*-
# created by Src - 一路好时光


import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# 发件人和收件人的邮箱地址
sender_email = 'srchao007@163.com'
receiver_email = 'srchao007@163.com'
password = 'GJAANJNROECTMCEK'

# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = '学python发送的第三封邮件html'

# 添加邮件正文
# body = ("<h5>这是一封测试邮件，包含正文内容。</h5>"+
#         "test，<a href='http://www.baidu.com'>baidu</a>")
body = '''
    <h5>这是一封测试邮件，包含正文内容。</h5>
    test，<a href='http://www.baidu.com'>baidu</a>
'''
msg.attach(MIMEText(body, 'html'))

# # 添加附件（如果有的话）
filename = 'my_first_mod.py'  # 假设附件是当前目录下的example.txt文件
with open(filename, 'rb') as attachment:
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', f'attachment; filename= {filename}')
    msg.attach(part)

# 连接到SMTP服务器并发送邮件
server = None
try:
    server = smtplib.SMTP_SSL('smtp.163.com', 465)  # 使用SSL连接
    server.login(sender_email, password)
    text = msg.as_string()
    server.sendmail(sender_email, receiver_email, text)
    print("邮件发送成功")
except Exception as e:
    print(f"邮件发送失败：{e}")
finally:
    server.quit()
